from fastapi import FastAPI
from pydantic import BaseModel
import uvicorn
from starlette.middleware.cors import CORSMiddleware
from configparser import ConfigParser


app = FastAPI(title="fast api demo",
              description="用于演示 fast api",
              version='0.2.1')
# 跨域 , 允许所有
origins = ["*"]
app.add_middleware(
    CORSMiddleware,
    allow_origins=origins,  #设置允许的origins来源
    allow_credentials=True,
    allow_methods=["*"],  # 设置允许跨域的http方法，比如 get、post、put等。
    allow_headers=["*"]  #允许跨域的headers，可以用来鉴别来源等作用。
)

# default
config = ConfigParser()
config.read('config.ini')
uvicorn_config = config['uvicorn']
uvicorn_host = uvicorn_config['host']
uvicorn_port = int(uvicorn_config['port'])


class Item(BaseModel):
    name: str
    price: float
    is_offer: bool = None

@app.get("/", summary="首页")
def read_root():
    return {"Hello": "FastAPI"}

@app.get("/items/{item_id}")
def read_item(item_id: int, q: str = None):
    return {"item_id": item_id, "q": q }

# 升级示例
@app.put("/items/{item_id}")
def update_item(item_id: int, item: Item):
    return {"item_name": item.name, "item_id": item_id}

if __name__ == '__main__':
    uvicorn.run("main:app", port=uvicorn_port, reload = True ,host = uvicorn_host)